/********************************************************
* Projet Chat System
* 
* Yann MBOUNGOU et Jean-Christophe VENDOME
* ELEVES INGENIEUR - 4e Année - Informatique et Réseaux
* INSA TOULOUSE, Dept. GEI - 2014 - 2015
*********************************************************/
package GUI;
import Interfaces.*;
import Controller.ChatController;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import javax.swing.*;
import Attach.*;
import Sons_Nouveau_Msg.SonSimple;
import java.net.InetAddress;


public class ChatGUI extends Graphisme implements FromUser, ToUser, ActionListener {
    private ChatController chatController;
    private final ArrayList <User> userList;
    private static boolean connected=false;
    private JFileChooser  fileDialog;
    private File file_joined ;
    private final MouseListener list; 
    private MsgPrivate prive=null; 
    
    @SuppressWarnings({"LeakingThisInConstructor", "Convert2Diamond"})
    public ChatGUI()
    {        
        super();
        connect.addActionListener(this);
        send.addActionListener(this);
        disc.addActionListener(this);
        File.addActionListener(this);
        this.userList=new ArrayList <User>();
        list = new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) 
            {
                 if (e.getClickCount() == 2)
                 {
                     String m=""+getjUserList().getSelectedValue();
                     if(m.equals("users LIST's")==false)
                     {
                        int index = getjUserList().locationToIndex(e.getPoint());                     
                        System.out.println("Double clicked on "+getjUserList().getSelectedValue()+": [Item="+index+"]");                     
                        
                        for(User u: getUserList())
                       {
                            if(u.getLogin().equals(m))
                            {
                                prive(u); 
                                u.setmsgPrive(true);
                            }
                       }     
                        
                    }                    
                }
            }};
        getjUserList().addMouseListener(list);
    }
    //*************************************************//
    public void prive(User u)
    {
       prive=new MsgPrivate(u); 
       prive.setGui(this); 
    }
    
    public void changePanel(JPanel p)
    {
       mainPanel.removeAll();
       mainPanel.add(p); //ajoute un panel en parametre
       mainPanel.add(msgPanel);
       mainPanel.validate();
       mainPanel.repaint();
    }

    //*************************************************//
     @Override
    @SuppressWarnings("ObjectEqualsNull")
    public void connect()                                                                                                                      
    {      
        String m=""+displayLogin();
        String m2="";
        msg.setText(""); 
        if(m.equals(m2))
        {
            msg.append(java.awt.Color.red, "Veuillez  saisir  un  login \n");
        }
        else
        {
            connected();
            getChatController().performConnect(displayLogin());
            changePanel(sendPanel);                     
            scroll2.setViewportView(getjUserList()); 
        }
       
    }
    
     @Override
    public void disconnect()                                                                          
    {        
        getChatController().performDisConnect();
        changePanel(authPanel);        
        disconnected();
    }
    
    @Override
    public void send()                                                                                        
    {
        msg.append(java.awt.Color.blue,displayLogin());
        msg.append(" : "+jftmessage.getText()+"\n"); 
        getChatController().performSend(displayLogin(),jftmessage.getText());
    }
        
    @Override
    public void open()
    {
        if (fileDialog == null) 
        {
            fileDialog = new JFileChooser();    
            fileDialog.addChoosableFileFilter(new ImageFilter());//(Accept All) file filter.
            fileDialog.setAcceptAllFileFilterUsed(false);//Add a custom file filter and disable the default	    
            fileDialog.setFileView(new ImageFileView());//Add custom icons for file types.	    
            fileDialog.setAccessory(new ImagePreview(fileDialog));//Add the preview pane.
        }
        int returnVal = fileDialog.showDialog(this,"Join File");
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            file_joined = fileDialog.getSelectedFile();
            msg.append(java.awt.Color.black,getFile_joined().getName()+ " joined .\n");
        } 
        else 
        {
            msg.append(java.awt.Color.red,"Attachment cancelled by "+displayLogin()+".\n");
        }
        msg.setCaretPosition(msg.getDocument().getLength());        
        fileDialog.setSelectedFile(null);//Reset the file chooser for the next time it's shown.
    }   
      
    @Override
    public void actionPerformed(ActionEvent e)
    {
        Object obj=e.getSource();
        if (obj instanceof JButton)
        {
           JButton b=(JButton)obj;
           if (b==connect) connect();
           else if (b==disc) disconnect();
           else if (b==send) send();
           else if (b==File) open();
        }
    }
    //**********************Update_List and Disconnect***************************//    
    public void performList(String login,InetAddress addr)            
    {
        Boolean inList = false;
        System.out.println("performList et connected="+connected);
        if(connected)
        {
            for(User u: getUserList())
            {
                System.out.println(u+" - ");
                if(u.getAddr().equals(addr))
                {
                   u.setLogin(login);
                   inList=true;
                }
            } 
            if(inList==false)
            {
              User u=new User(login,addr);
              msg.append(java.awt.Color.blue,u.getLogin());
              msg.append(" is connected\n"); 
              getUserList().add(u);
              displayUserList();  
            }
            else
            {
               displayUserList();  
            }
            
            
        }       
    }
    
    public void performBye(String login)            
    {
        System.out.println("performBye et connected="+connected);
        if(connected)
        {
            for(User u: getUserList())
            {
                System.out.println(u+" - ");
                if(u.getLogin().equals(login))  
                {
                    msg.append(java.awt.Color.blue,u.getLogin());
                    msg.append(" is disconnected\n"); 
                    getUserList().remove(u);                 
                }
            }            
            displayUserList();                            
        }
        
    }
  
    //*********************Receive Text**************************//
    @Override
    @SuppressWarnings("ResultOfObjectAllocationIgnored")
    public void ReceiveMsg(String login, String message)
    {
        if(connected)
        {
           new SonSimple();
            System.out.println("ReceiveMsg public");
            msg.append(java.awt.Color.green,login+" :");
            msg.append(message+"\n"); 
        }
    }
    //*********************Receive Text**************************//
    @SuppressWarnings("ResultOfObjectAllocationIgnored")
    public void ReceiveMsgPriv(String login, String message)
    {
        if(connected)
        {
            Boolean test = false;
            new SonSimple();
            System.out.println("ReceiveMsg private");
            for(User u: getUserList())
            {
                if(u.getLogin().equals(login))
                {
                    if(u.getmsgPrive().equals(false))
                    {
                        prive(u);  
                        prive.getDisp().append(java.awt.Color.green,login+" :");
                        prive.getDisp().append(message+"\n");
                        test = true;
                    }
                }
            }   
            if(test == false)
            {
                prive.getDisp().append(java.awt.Color.green,login+" :");
                prive.getDisp().append(message+"\n");
            }   
        }        
    }
    
    //**********************Print Login***************************//
    @Override
    public void displayUserList()
    {
        getjUserList().setListData(getUserList().toArray());
    }

    public void setChatController(ChatController chatController) {
        this.chatController = chatController;
    }

    @Override
    public String displayLogin() {
        return getJftlogin().getText();
    }

    @Override
    public void connected() {
        connected=true;
        msg.setText("");
        msg.setText(""); 
        msg.append(java.awt.Color.blue,displayLogin());
        msg.append(" is connected\n");  
    }

    @Override
    public void disconnected() {
        connected=false;
        msg.setText("");
        msg.setText("");        
        msg.append(java.awt.Color.blue,displayLogin());
        msg.append(" is disconnected \n");        
        for(User u: getUserList())
            {                
                getUserList().remove(u);                 
            }            
        displayUserList();
        getJftlogin().setText("");
        for(User u: getUserList())
        {
                getUserList().remove(u); 
        }            
        displayUserList();  
        getJftlogin().setText("");        
    }

    //*********************File joinned****************************//
    public File getFile_joined() {
        return file_joined;
    }

    @Override
    public void back() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public ArrayList <User> getUserList() {
        return userList;
    }

    public ChatController getChatController() {
        return chatController;
    }

    @Override
    public void openPrivate() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
}


